<template>
	<view class="goods-detail" :class="themeName">
		<navbar title="商品详情" :background="{ background: `rgba(256,256,256,${percent})` }"
			:titleColor="`rgba(0,0,0,${percent})`" :immersive="true"></navbar>
		<bubble top="220rpx" :page="2" :discharge="isDischarge"></bubble>
		<!-- 轮播图 -->
		<goods-swiper :images="goodsInfo.goods_image" :video="goodsInfo.video" :video-cover="goodsInfo.video_cover" />
		<!-- 秒杀信息 -->
		<view class="goods-seckill">
			<view class="goods-seckill__price">
				<price :content="activityInfo.min_seckill_price" main-size="46rpx" minor-size="32rpx"
					:prefix="$zhTran('秒杀价') + goodsInfo.price_symbol" color="#FFFFFF" />
				<price class="m-l-12" :content="goodsInfo.min_price" color="#ffffff" :prefix="goodsInfo.price_symbol"
					:line-through="true" />
			</view>

			<view class="goods-seckill__time">
				<text class="xs m-b-10" :style="{ color: themeColor }">{{$zhTran('距离结束还剩')}}</text>
				<count-down :time-end="activityInfo.end_time" />
			</view>
		</view>
		<!-- 商品基础信息 -->
		<view class="goods-info">
			<view class="flex row-between col-top m-b-30">
				<view class="goods-name lg m-r-20">{{ goodsInfo.name }}</view>
				<view class="sm lighter share flex-none" @tap="showShare = true">
					<u-icon name="share" />
					<text class="m-l-10">{{$zhTran('分享')}}</text>
				</view>
			</view>
			<view class="flex row-between muted xs">
				<template v-if="goodsInfo.stock_show">
					<view>{{$zhTran('库存')}}: {{ goodsInfo.total_stock }}</view>
				</template>
				<view>{{$zhTran('已抢')}}: {{ activityInfo.sales_volume }}</view>
				<view>{{$zhTran('浏览量')}}: {{ activityInfo.browse_volume }}</view>
			</view>
		</view>
		<view class="nr specification">
			<text class="muted flex-none">{{$zhTran('运费')}}</text>
			<text class="m-l-20">{{ goodsInfo.free_shipping_tips || $zhTran('以提交订单时为准') }}</text>
		</view>
		<!-- S 规格 -->
		<view class="nr specification" @click="onGoodsOptions">
			<text class="muted flex-none">{{$zhTran('已选')}}</text>
			<text class="m-l-20">{{ specValueStr }}</text>
			<u-icon name="arrow-right" class="muted" style="margin-left: auto" />
		</view>

		<!-- 规格选择Popup -->
		<goods-spec v-model="showGoodsSpec" :defaultInfo="{
			image: goodsInfo.image,
			price: activityInfo.min_seckill_price,
			stock: goodsInfo.total_stock,
			unit: goodsInfo.unit_name,
		}" price-key="seckill_price" :spec-list="goodsInfo.spec_value" :spec-map="goodsInfo.spec_value_list"
			:prefix="goodsInfo.price_symbol" :goods="goodsInfo.id" :buttons="specButtonsList" @buy="handleBuy"
			@change="changeGoodsSpec" :understock_order_enabled="goodsInfo.understock_order_enabled" />
		<!-- E 规格 -->

		<!-- diy -->
		<view v-for="(item, index) in pagesData" :key="index">
			<template v-if="item.name == 'reviews'">
				<w-reviews v-if="item.show" :content="item.content" :styles="item.styles" :comment="goodsComment"
					:goods-id="goodsID" />
			</template>
			<template v-if="item.name == 'goodsrecom'">
				<w-goodsrecom v-if="item.show" :content="item.content" :styles="item.styles" />
			</template>
		</view>

		<!-- 商品介绍 -->
		<view class="detail">
			<view class="detail-title nr">{{$zhTran('商品详情')}}</view>
			<u-parse :html="goodsInfo.content" :show-with-animation="true"></u-parse>
		</view>

		<w-jishuzhichi />

		<!-- 功能按钮组 -->
		<view class="functions">
			<view class="icon-group">
				<view class="icon-item" @tap="goService">
					<u-icon name="kefu-ermai" size="42" />
					<text>{{$zhTran('客服')}}</text>
				</view>
				<view class="icon-item" @tap="changeCollect(isGoodsCollect)">
					<template v-if="isGoodsCollect">
						<u-icon name="star-fill" size="42" :color="themeColor" />
					</template>
					<template v-else>
						<u-icon name="star" size="42" />
					</template>
					<text>{{$zhTran('收藏')}}</text>
				</view>
				<!-- <view class="icon-item" @tap="goCart">
					<u-icon name="shopping-cart" size="42" />
					<text>{{$zhTran('购物车')}}</text>
				</view> -->
			</view>
			<view class="button-group">
				<view class="button-item button-item--cart">
					<router-link :to="{
						path: '/bundle2/pages/goods_detail/goods_detail',
						query: { id: goodsInfo.id },
					}">
						{{$zhTran('原价购买')}}</router-link>
				</view>

				<view class="button-item button-item--buy" @click="onBuy">{{$zhTran('立即抢购')}}</view>
			</view>
		</view>
		<share-popup v-model="showShare" :share-id="seckillID" page-path="bundle/pages/seckill_detail/seckill_detail"
			:type="2" />
		<!-- 页面状态 -->
		<page-status :status="pageStatus">
			<template #error>
				<u-empty :text="pageErrorMsg" :src="$getImageUri('resource/image/shopapi/uniapp/empty/shop.png')"
					:icon-size="280"></u-empty>
			</template>
		</page-status>
		<u-back-top :scroll-top="scrollTop" :top="1000" :customStyle="{
			backgroundColor: '#FFF',
			color: '#000',
			boxShadow: '0px 3px 6px rgba(0, 0, 0, 0.1)',
		}"></u-back-top>
	</view>
</template>

<script>
	import {
		apiSeckillDetail
	} from "@/api/activity";
	import {
		apiCouponGet
	} from "@/api/store";
	import {
		apiGoodsCollect,
		apiGoodsMarketing
	} from "@/api/goods";

	import {
		apiGetPage
	} from "@/api/store";
	import {
		PageStatusEnum
	} from "@/utils/enum";
	import {
		mapGetters
	} from "vuex";
	import {
		strToParams
	} from "@/utils/tools";
	import {
		OrderTypeEnum
	} from "@/utils/enum";

	export default {
		name: "GoodsDetail",

		data() {
			return {
				isDischarge: false,
				// 页面状态
				pageStatus: PageStatusEnum["LOADING"],
				pagesData: [],
				pageErrorMsg: "", // 页面异常信息
				scrollTop: 0,
				percent: 0,
				showShare: false,
				goodsInfo: {}, // 商品信息
				goodsComment: {}, // 用户评价
				seckillID: "", // 秒杀ID
				goodsID: "", // 商品ID
				isGoodsCollect: false, // 商品收藏

				showGoodsSpec: false, // 商品规格: 显示 | 隐藏
				goodsSpecOptions: {}, // 已选商品规格
				specButtonsList: [], // 规格按钮

				// 规格按钮组
				specButtonsGroups: {
					buy: {
						event: "buy",
						text: this.$zhTran("立即抢购"),
					},
				},
				activityInfo: {},
			};
		},

		computed: {
			...mapGetters(["isLogin"]),

			// 已选商品规格
			specValueStr() {
				return this.goodsSpecOptions?.spec?.spec_value_str ?? "";
			},
		},

		methods: {
			// 获取装修页面
			getPage() {
				apiGetPage({
					type: 5,
					goods_id: this.goodsID,
				}).then((data) => {
					const {
						common,
						content
					} = data;

					this.pagesData = this.$zhTran(content);
					uni.setNavigationBarTitle({
						title: this.$zhTran(common.title),
					});
				});
			},
			// 更改规格
			changeGoodsSpec(options) {
				this.goodsSpecOptions = options;
				console.log(options);
			},

			// 点击加入购物车按钮
			onCart() {
				this.showGoodsSpec = true;
				this.specButtonsList = [this.specButtonsGroups.cart];
			},

			// 更改商品收藏状态
			changeCollect(value) {
				value = !!value ? 0 : 1;
				if (!this.isLogin) return this.$Router.push("/bundle2/pages/login/login");

				apiGoodsCollect({
						goods_id: this.goodsID,
						is_collect: value,
					})
					.then((data) => {
						this.isGoodsCollect = value;
					})
					.catch((err) => {
						console.log(err);
					});
			},

			// 去客服
			goService() {
				this.$Router.push({
					path: "/bundle/pages/service/service",
					query: {
						type: "seckill",
						goods_id: this.goodsID,
						activity_id: this.seckillID,
					},
				});
			},

			// 去购物车
			goCart() {
				this.$Router.replaceAll({
					path: "/bundle2/pages/shop_cart/shop_cart",
				});
			},

			// 点击立即购买按钮
			onBuy() {
				this.showGoodsSpec = true;
				this.specButtonsList = [this.specButtonsGroups["buy"]];
			},

			// 点击已选规格
			onGoodsOptions() {
				this.showGoodsSpec = true;
				this.specButtonsList = [this.specButtonsGroups["buy"]];
			},

			// 处理 立即购买
			handleBuy({
				spec,
				number
			}) {
				// this.$Router.push({
				// 	path: "/bundle2/pages/goods_order/goods_order",
				// 	query: {
				// 		from: OrderTypeEnum["SECKILL"],
				// 		payload: {
				// 			seckill_id: this.activityInfo?.id,
				// 			goods: [{
				// 				goods_num: number,
				// 				item_id: spec.id,
				// 			},],
				// 		},
				// 	},
				// });
				var that = this
				uni.navigateTo({
					url: "/bundle2/pages/goods_order/goods_order",
					events: {
						reCountCarNum(res) {
							that.$store.dispatch("getCartNum");
						}
					},
					success(res) {
						res.eventChannel.emit("receiveData", {
							from: OrderTypeEnum["SECKILL"],
							payload: {
								seckill_id: that.activityInfo?.id,
								goods: [{
									goods_num: number,
									item_id: spec.id,
								}, ],
							},
						});
					}
				});
			},

			// 初始化商品详情数据
			initGoodsDetail() {
				return new Promise((resolve, reject) => {
					apiSeckillDetail({
							id: this.seckillID,
						})
						.then((ndata) => {
							let data = this.$zhTran(ndata)
							this.goodsInfo = data;
							this.goodsID = data.id;
							this.activityInfo = data.activity;
							const hasComment = JSON.stringify(data.goods_comment) !== "[]";
							this.goodsComment = hasComment ? data.goods_comment : {};
							this.isGoodsCollect = !!data.is_collect;
							return data;
						})
						.then((data) => {
							// #ifdef H5
							// 设置分享
							this.$store.dispatch("setWxShare", {
								shareImage: data?.image,
								shareDesc: this.$zhTran(data?.name),
							});
							// #endif
							resolve(data);
						})
						.catch((err) => {
							reject(err);
						});
				});
			},
		},
		onPageScroll(e) {
			const top = uni.upx2px(100);
			const {
				scrollTop
			} = e;
			this.percent = scrollTop / top > 1 ? 1 : scrollTop / top;
			this.scrollTop = scrollTop;
		},
		async onLoad() {
			const options = this.$Route.query;

			// 商品ID赋值：点击 | 扫码
			this.seckillID = options["scene"] ? strToParams(options["scene"])["id"] : options.id;

			try {
				if (!this.seckillID) throw new Error(this.$zhTran("该商品不存在"));

				// 商品详情数据
				await this.initGoodsDetail();
				// diy信息
				await this.getPage();
				this.pageStatus = PageStatusEnum["NORMAL"];
			} catch (errMsg) {
				console.log(errMsg);
				this.pageErrorMsg = errMsg;
				this.pageStatus = PageStatusEnum["ERROR"];
			}
		},

		onShareAppMessage() {
			const {
				name,
				image
			} = this.goodsInfo;
			return {
				title: name,
				path: `/bundle/pages/seckill_detail/seckill_detail?id=${this.seckillID}&invite_code=${this.userInfo.code}`,
				imageUrl: image,
			};
		},
		onHide() {
			this.isDischarge = true;
		},
		onShow() {
			this.isDischarge = false;
		},
	};
</script>

<style lang="scss" scoped>
	.goods-detail {
		padding-bottom: calc(100rpx + 20rpx + constant(safe-area-inset-bottom));
		padding-bottom: calc(100rpx + 20rpx + env(safe-area-inset-bottom));
	}

	.goods-seckill {
		display: flex;
		height: 100rpx;

		&__price {
			flex: 1;
			display: flex;
			align-items: center;
			padding: 0 20rpx;
			@include background_linear();
		}

		&__time {
			display: flex;
			flex-direction: column;
			align-items: center;
			justify-content: center;
			width: 240rpx;
			@include background_color(0.3);
		}
	}

	.goods-info {
		padding: 20rpx 24rpx;
		background-color: #ffffff;

		.share {
			display: flex;
			justify-content: center;
			align-items: center;
			width: 134rpx;
			height: 60rpx;
			margin-right: -24rpx;
			border-radius: 30px 0 0 30px;
			background-color: #f6f6f6;
		}

		.goods-name {
			font-weight: 500;
		}
	}

	.discounts {
		display: flex;
		padding: 24rpx;
		margin-top: 20rpx;
		background-color: #ffffff;

		.coupon-tag {
			box-sizing: border-box;
			position: relative;
			display: flex;
			justify-content: center;
			min-width: 140rpx;
			height: 36rpx;
			padding: 0 20rpx;
			border-radius: 4px;
			margin-right: 10rpx;
			color: #ffffff;

			@include background_color();

			&::before,
			&::after {
				position: absolute;
				top: 50%;
				transform: translateY(-50%);
				display: block;
				content: "";
				width: 10rpx;
				height: 10rpx;
				border-radius: 50%;
				background-color: #ffffff;
			}

			&::before {
				right: -5rpx;
			}

			&::after {
				left: -5rpx;
			}
		}
	}

	.specification {
		display: flex;
		padding: 24rpx;
		margin-top: 20rpx;
		background-color: #ffffff;
	}

	.detail {
		padding: 24rpx;
		margin-top: 20rpx;
		background-color: #ffffff;

		&-title {
			text-align: center;
			font-weight: 500;
			padding-bottom: 24rpx;
		}

		::v-deep image {
			vertical-align: top;
		}

		// #ifdef H5
		::v-deep img {
			vertical-align: top;
			display: inline;
		}

		// #endif
		// #ifdef MP-WEIXIN || APP-PLUS
		::v-deep ._img {
			vertical-align: top;
			display: inline;
		}

		// #endif
	}

	.functions {
		position: fixed;
		left: 0;
		right: 0;
		bottom: 0;
		display: flex;
		align-items: center;
		height: calc(100rpx + constant(safe-area-inset-bottom));
		height: calc(100rpx + env(safe-area-inset-bottom));
		padding: 0 24rpx constant(safe-area-inset-bottom) 24rpx;
		padding: 0 24rpx env(safe-area-inset-bottom) 24rpx;
		border-top: $-solid-border;
		background-color: #ffffff;

		.icon-group {
			display: flex;
			justify-content: space-around;
			font-size: $-font-size-xxs;
			color: $-color-lighter;

			.icon-item {
				width: 90rpx;
				display: flex;
				flex-direction: column;
				align-items: center;
			}
		}

		.button-group {
			flex: 1;
			display: flex;
			justify-content: space-between;

			.button-item {
				flex: 1;
				box-sizing: border-box;
				display: flex;
				justify-content: center;
				align-items: center;
				height: 74rpx;
				margin-left: 14rpx;
				border-radius: 60px;

				&--cart {
					@include font_color();
					@include border_color();

					border-width: 1px;
					border-style: solid;
				}

				&--buy {
					@include background_color();
					color: #ffffff;
				}
			}
		}
	}

	.coupons {
		background-color: #f6f6f6;

		&-header {
			display: flex;
			align-items: center;
			justify-content: space-between;
			height: 100rpx;
			padding: 0 30rpx;
			font-weight: 500;
			font-size: $-font-size-md;
			background-color: #ffffff;
		}

		&-main {
			padding: 20rpx;

			.coupons-item {
				&:nth-child(n + 2) {
					margin-top: 20rpx;
				}
			}
		}
	}
</style>